package com.yanfan.energy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.model.LoginUser;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.energy.domain.*;
import com.yanfan.energy.domain.enums.BillTypeEnums;
import com.yanfan.energy.domain.enums.TaskEventTypeEnums;
import com.yanfan.energy.domain.model.ComboBoxBody;
import com.yanfan.energy.domain.statist.AttendanceStatistics;
import com.yanfan.energy.domain.statist.DateStatistics;
import com.yanfan.energy.domain.statist.OrderStatistics;
import com.yanfan.energy.mapper.*;
import com.yanfan.energy.service.ExcelService;
import com.yanfan.energy.service.ProductionService;
import com.yanfan.energy.util.DateUtils;
import com.yanfan.energy.util.DoubleOperation;
import com.yanfan.energy.util.SerialNumberUtil;
import com.yanfan.energy.util.WidgetUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author caijinkang
 * @date 2022年12月08日 9:20
 */
@Service("ProductionServiceImpl")
@Transactional(rollbackFor = Exception.class)
class ProductionServiceImpl implements ProductionService {


    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    DispatchListServiceImpl dispatchListService;
    @Resource
    AssignmentTemplateTaskDao assignmentTemplateTaskDao;
    @Resource
    private PerformanceDao performanceDao;
    @Resource
    private ProductionDao productionDao;
    @Resource
    private BatchDao batchDao;
    @Resource
    private OrderDetailsDao orderDetailsDao;
    @Resource
    private MaterialDao materialDao;
    @Resource
    private StationRecordDao stationRecordDao;
    @Resource
    private EmployeePersonalDao employeePersonalDao;
    @Resource
    private AttendanceRecordDao attendanceRecordDao;
    @Resource
    private StationRecordsDao stationRecordsDao;
    @Resource
    private MaterialsDao materialsDao;
    @Resource
    private OrderLineDetailsDao orderLineDetailsDao;
    @Resource
    private MaterialRecordsDao materialRecordsDao;
    @Resource
    private SchedulesDao schedulesDao;
    @Resource
    private ApprovalsDao approvalsDao;
    @Resource
    private AssignmentsDao assignmentsDao;
    @Resource
    private TaskMaterialApproveDao taskMaterialApproveDao;
    @Resource
    private BatchSegmentationDao batchSegmentationDao;
    /**
     * 图片
     */
    @Resource
    private DispatchListDao dispatchListDao;
    @Autowired
    private ExcelService excelService;

    @Override
    public AjaxResult findPerformance(Integer currPage, Integer pageSize, String date) {
        PageHelper.startPage(currPage, pageSize);
        List<Performance> result = performanceDao.findPerformance(date);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findProduction(Integer currPage, Integer pageSize, Integer type) {
        PageHelper.startPage(currPage, pageSize);
        List<Production> result = productionDao.findProduction();
        if (!Objects.isNull(type)) {
            return AjaxResult.success(new PageInfo<>(result
                                                             .stream()
                                                             .filter(s -> !s.getType().equals(type))
                                                             .collect(Collectors.toList())));
        }
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findBatchManagement(Integer currPage, Integer pageSize, Integer type) {
        PageHelper.startPage(currPage, pageSize);
        List<Batch> result = batchDao.findBatchManagement();
        if (!Objects.isNull(type)) {
            return AjaxResult.success(new PageInfo<>(result
                                                             .stream()
                                                             .filter(s -> !s.getType().equals(type))
                                                             .collect(Collectors.toList())));
        }
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findOrderManagement(Integer currPage, Integer pageSize, Integer type) {
        PageHelper.startPage(currPage, pageSize);
        List<OrderDetails> result = orderDetailsDao.findOrderManagement();
        if (!Objects.isNull(type)) {
            return AjaxResult.success(new PageInfo<>(result
                                                             .stream()
                                                             .filter(s -> !s.getType().equals(type))
                                                             .collect(Collectors.toList())));
        }
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findMaterials(Integer currPage, Integer pageSize) {
        PageHelper.startPage(currPage, pageSize);
        List<Material> result = materialDao.findMaterials();
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findStationRecord(Integer currPage, Integer pageSize) {
        PageHelper.startPage(currPage, pageSize);
        List<StationRecord> result = stationRecordDao.findStationRecord();
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findAttendanceRate(String range, String begin, String end) {
        List<DateStatistics> result = attendanceRecordDao.findAttendanceRate();
        result.stream().forEach(r -> {
            if ("0".equals(r.getDate())) {
                r.setDate("出勤");
            }
            if ("1".equals(r.getDate())) {
                r.setDate("事假");
            }
            if ("2".equals(r.getDate())) {
                r.setDate("病假");
            }
            if ("3".equals(r.getDate())) {
                r.setDate("其他");
            }
        });
        AttendanceStatistics attendanceStatistics = new AttendanceStatistics();
        // 出勤统计
        attendanceStatistics.setList(result);
        // 工位出勤率
        attendanceStatistics.setRate(95.20);
        // 到岗人次
        attendanceStatistics.setArrival(87);
        // 开机数量
        attendanceStatistics.setStarting(38);
        // 已处理任务总数
        attendanceStatistics.setTask(78);

        attendanceStatistics.setProcessedBatch(122);
        attendanceStatistics.setAvgProcessedTime(14.5);

        if (attendanceStatistics != null) {
            return AjaxResult.success(attendanceStatistics);
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findOccupation() {
        List<DateStatistics> result = employeePersonalDao.findOccupation();
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findStationRecords(StationBody stationBody) {
        PageHelper.startPage(stationBody.getCurrPage(), stationBody.getPageSize());
        List<StationRecords> result = stationRecordsDao.findStationRecords(stationBody);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public AjaxResult addStationRecords(StationRecords stationRecords) {
        if (!Objects.isNull(stationRecords)) {
            stationRecords.setOperator(SecurityUtils.getUsername());
            stationRecords.setCreatedBy(SecurityUtils.getUsername());
            stationRecords.setPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());
            // 设置初始的状态为使用中
            // stationRecords.setState(1);

            // 从人员生产信息来获取位置信息
            stationRecords.setStationNumber(SerialNumberUtil.createStationNo());
            if (Objects.isNull(stationRecords.getStationName())) {
                stationRecords.setStationName("1#填装位");
            }
            if (Objects.isNull(stationRecords.getLocation())) {
                stationRecords.setLocation("厂区二号车间");
            }
            stationRecords.setLocation("厂区一号车间");

            int i = stationRecordsDao.insert(stationRecords);
            if (i > 0) {
                return AjaxResult.success("新增成功");
            }
        }
        return AjaxResult.error("新增失败");
    }

    @Override
    public AjaxResult updateStationRecords(StationRecords stationRecords) {
        if (Objects.isNull(stationRecords)) {
            return AjaxResult.error("入参为空");
        }
        int i = stationRecordsDao.update(stationRecords);
        if (i > 0) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }

    @Override
    public void stationRecordsByReport(HttpServletResponse response) {
        List<StationRecords> result = stationRecordsDao.findStationRecords(null);
        if (result != null && result.size() > 0) {
            try {
                excelService.downloadByStationRecords(StationRecords.class, result, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public AjaxResult findMaterialsInformation(MaterialsBody materialsBody) {
        PageHelper.startPage(materialsBody.getCurrPage(), materialsBody.getPageSize());
        List<Materials> result = materialsDao.findMaterialsInformation(materialsBody);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public AjaxResult addMaterialsInformation(Materials materials) {
        if (!Objects.isNull(materials)) {
            Materials classifyName = materialsDao.findMaterialsByClassifyNumber(materials.getClassifyNumber());
            materials.setClassifyName(classifyName.getClassifyName());
            materials.setCreatedBy(SecurityUtils.getUsername());
            int i = materialsDao.insert(materials);
            if (i > 0) {
                return AjaxResult.success("新增成功");
            }
        }
        return AjaxResult.error("新增失败");
    }

    @Override
    public AjaxResult updateMaterialsInformation(Materials materials) {
        if (Objects.isNull(materials)) {
            return AjaxResult.error("入参为空");
        }
        int i = materialsDao.update(materials);
        if (i > 0) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }

    @Override
    public AjaxResult findMaterialsRecords(MaterialRecordsBody materialRecordsBody) {
        PageHelper.startPage(materialRecordsBody.getCurrPage(), materialRecordsBody.getPageSize());
        List<MaterialRecords> result = materialRecordsDao.findMaterialsRecords(materialRecordsBody);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public void materialsInformationByReport(HttpServletResponse response) {
        List<Materials> result = materialsDao.findMaterialsInformation(null);
        if (result != null && result.size() > 0) {
            try {
                excelService.downloadByMaterials(Materials.class, result, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public AjaxResult updateMaterialsNumber(Materials materials) {
        // 如果出库的数量大于库存下限则提示
        if (materials
                .getType()
                .equals(2) && materials.getQuantity() - materials.getAfterQuantity() < materials.getLowerQuantity()) {
            return AjaxResult.error("入库的数量大于库存下限的数量");
        } else {
            //修改物料表的数量
            Materials materialsUpdate = new Materials();
            //添加一条物料信息记录
            MaterialRecords materialRecords = new MaterialRecords();
            materialRecords.setMaterialNumber(materials.getNumber());
            materialRecords.setType(materials.getType());
            materialRecords.setBeforeQuantity(materials.getQuantity());
            materialRecords.setCountQuantity(materials.getAfterQuantity());
            // 判断是出库还是入库的操作：1、入库，2、出库
            if (materials.getType() == 1) {
                materialRecords.setAfterQuantity(materials.getQuantity() + materials.getAfterQuantity());
                materialsUpdate.setQuantity(materials.getQuantity() + materials.getAfterQuantity());
            } else if (materials.getType() == 2) {
                materialRecords.setAfterQuantity(materials.getQuantity() - materials.getAfterQuantity());
                materialsUpdate.setQuantity(materials.getQuantity() - materials.getAfterQuantity());
            }
            materialRecords.setOperator(SecurityUtils.getUsername());
            materialRecords.setOperatorDate(new Date());
            materialRecords.setOrderId(materials.getOrderId());
            materialRecords.setRemarks(materials.getRemarks());
            materialRecords.setCreatedBy(SecurityUtils.getUsername());
            materialRecords.setCreatedDate(new Date());
            int i = materialRecordsDao.insert(materialRecords);

            materialsUpdate.setId(materials.getId());
            int u = materialsDao.update(materialsUpdate);
            if (i > 0 && u > 0) {
                return AjaxResult.success("出入库操作成功");
            }
        }

        return AjaxResult.error("出库或者入库失败");
    }

    @Override
    public void materialsRecordsByReport(HttpServletResponse response) {
        List<MaterialRecords> result = materialRecordsDao.findMaterialsRecords(null);
        if (result != null && result.size() > 0) {
            try {
                excelService.downloadByMaterialRecords(MaterialRecords.class, result, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public AjaxResult findOrderLineDetails(OrderBody orderBody) {
        PageHelper.startPage(orderBody.getCurrPage(), orderBody.getPageSize());
        List<OrderLineDetails> result = orderLineDetailsDao.findOrderLineDetails(orderBody);
        if (result != null && result.size() >= 0) {
            // 订单关联任务的人数，现在任务都只分配一个人
            result.stream().forEach(re -> {
                re.setPeopleNumber(1);
            });
            if (orderBody.isMobileFlag()) {
                // 如果当前用户是管理员
                if (SecurityUtils.getLoginUser().getUser().isAdmin()) {
                    return AjaxResult.success(new PageInfo<>(result
                                                                     .stream()
                                                                     .filter(re -> re
                                                                             .getType()
                                                                             .equals(orderBody.getState()))
                                                                     .collect(Collectors.toList())));
                } else {
                    return AjaxResult.success(new PageInfo<>(result
                                                                     .stream()
                                                                     .filter(re -> re
                                                                             .getType()
                                                                             .equals(orderBody.getState()) || re
                                                                             .getOperatorId()
                                                                             .equals(SecurityUtils
                                                                                             .getLoginUser()
                                                                                             .getUserId()))
                                                                     .collect(Collectors.toList())));
                }

            }

            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult addOrderLineDetails(OrderLineDetails orderLineDetails) {
        if (!Objects.isNull(orderLineDetails)) {
            orderLineDetails.setCreatedBy(SecurityUtils.getUsername());
            orderLineDetails.setOperatorId(SecurityUtils.getUserId().intValue());
            orderLineDetails.setPrincipal(SecurityUtils.getUsername());
            orderLineDetails.setTelephone(SecurityUtils.getLoginUser().getUser().getPhonenumber());
            // 如果为空生成订单编号
            if (Objects.isNull(orderLineDetails.getNumber())) {
                orderLineDetails.setNumber(SerialNumberUtil.createOrderNo());
            }
            int i = orderLineDetailsDao.insert(orderLineDetails);
            if (i > 0) {
                return AjaxResult.success("新增成功");
            }
        }
        return AjaxResult.error("新增失败");
    }

    @Override
    public AjaxResult updateOrderLineDetails(OrderLineDetails orderLineDetails) {
        if (Objects.isNull(orderLineDetails)) {
            return AjaxResult.error("入参为空");
        }
        int i = orderLineDetailsDao.update(orderLineDetails);
        if (i > 0) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }

    @Override
    public AjaxResult deleteOrderLineDetails(Integer id) {
        int i = orderLineDetailsDao.deleteById(id.longValue());
        if (i > 0) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult findOrderDetailsByBatches(OrderBody orderBody) {
        PageHelper.startPage(orderBody.getCurrPage(), orderBody.getPageSize());
        List<OrderLineDetails> result = orderLineDetailsDao.findOrderDetailsByBatches(orderBody);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findOrderLineDetailsByTarget() {
        // 查询所有的订单信息
        List<OrderLineDetails> result = orderLineDetailsDao.findAllOrderLineDetails();
        //创建返回展示七项的数据对象
        OrderStatistics orderStatistics = new OrderStatistics();
        if (result != null && result.size() > 0) {
            // 设置已完成订单数量
            orderStatistics.setFinished(result
                                                .stream()
                                                .filter(r -> r.getType() == 3)
                                                .collect(Collectors.toList())
                                                .size());
            // 设置待处理订单数量
            orderStatistics.setPending(result
                                               .stream()
                                               .filter(r -> r.getType() == 1)
                                               .collect(Collectors.toList())
                                               .size());
            // 设置处理中订单数量
            orderStatistics.setProgress(result
                                                .stream()
                                                .filter(r -> r.getType() == 2)
                                                .collect(Collectors.toList())
                                                .size());
            // 设置订单完成率 实际完成数量/计划完成数量
            orderStatistics.setPercentage(Double.valueOf(result
                                                                 .stream()
                                                                 .filter(r -> r.getType() == 3)
                                                                 .collect(Collectors.toList())
                                                                 .size() / result
                    .stream()
                    .collect(Collectors.toList())
                    .size() * 100));
            // 设置订单平均用时
            orderStatistics.setHour(12.00);
            // 设置上月同比
            orderStatistics.setYear(0.00);
            // 设置上月环比
            orderStatistics.setChain(0.00);
            if (orderStatistics != null) {
                return AjaxResult.success(orderStatistics);
            }
        }
        return AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult findSchedules(SchedulesBody schedulesBody) {
        PageHelper.startPage(schedulesBody.getCurrPage(), schedulesBody.getPageSize());
        List<Schedules> result = schedulesDao.findSchedules(schedulesBody);
        if (result != null && result.size() > 0) {

            if (schedulesBody.isMobileFlag()) {
                // 如果当前用户是管理员
                if (SecurityUtils.getLoginUser().getUser().isAdmin()) {
                    return AjaxResult.success(new PageInfo<>(result
                                                                     .stream()
                                                                     .filter(re -> re
                                                                             .getState()
                                                                             .equals(schedulesBody.getState()))
                                                                     .collect(Collectors.toList())));
                } else {
                    return AjaxResult.success(new PageInfo<>(result
                                                                     .stream()
                                                                     .filter(re -> re
                                                                             .getState()
                                                                             .equals(schedulesBody.getState()) || re
                                                                             .getPrincipal()
                                                                             .equals(SecurityUtils
                                                                                             .getLoginUser()
                                                                                             .getUsername()))
                                                                     .collect(Collectors.toList())));
                }

            }

            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    @Transactional
    public AjaxResult addSchedules(Schedules schedules) {
        if (!Objects.isNull(schedules)) {
            schedules.setNumber(SerialNumberUtil.createSchedulesNo());
            int i = schedulesDao.insert(schedules);

            // 判读生产排程下是否有批次
            if (!Objects.isNull(schedules.getSectionBatchedBodies())) {
                schedules.setCreatedBy(SecurityUtils.getUsername());
                schedules.getSectionBatchedBodies().stream().forEach(s -> {
                    //int sc = schedulesDao.findBatchesBySchedule(s.getBatchNumber(), schedules.getNumber());
                    /*// 如果没有对应的排程
                    if (sc <= 0) {
                        // 添加批次
                        int batches = batchDao.insertBatchByBatch(new Batches(null, s.getBatchNumber(), null, schedules.getOrderNumber(), null, null, 1, s.getBatchBeginDate(), s.getBatchEndDate(), null, null, null, null, null, Long.valueOf(s.getBatchShopId()), null, s.getBatchWorkshop(), SecurityUtils.getUsername(), null, null, null));
                        scheduleBatchesDao.insert(new ScheduleBatches(null, schedules.getId(), Long.valueOf(batches).longValue(), SecurityUtils.getUsername(), null, null));
                    } else if (sc > 0) {
                        // 如果找到了对应的排程下批次
                        batchDao.updateBatches(new Batches(null, s.getBatchNumber(), null, schedules.getOrderNumber(), null, null, 1, s.getBatchBeginDate(), s.getBatchEndDate(), null, null, null, null, null, Long.valueOf(s.getBatchShopId()), null, s.getBatchWorkshop(), SecurityUtils.getUsername(), null, null, null));
                    }*/
                    Batches batches = new Batches();
                    batches.setNumber(s.getBatchNumber());
                    batches.setBeginDate(s.getBatchBeginDate());
                    batches.setEndDate(s.getBatchEndDate());
                    batches.setWorkshopId(Objects.isNull(s.getBatchShopId()) ? null : Long
                            .valueOf(s.getBatchShopId())
                            .longValue());
                    batches.setCreatedBy(SecurityUtils.getUsername());
                    int bat = batchDao.updateBatches(batches);
                    // 判断批次下是否有分段
                    if (!Objects.isNull(s.getSectionList())) {
                        s.getSectionList().stream().forEach(sub -> {
                            //int seg = batchSegmentationDao.selectBatchAndSegmentation(s.getBatchNumber(), sub.getSectionNumber());
                            // 如果没有对应的批次
                            /*if (seg <= 0) {
                                // 添加分段
                                BatchSegmentation batchSegmentation = new BatchSegmentation();
                                batchSegmentation.setBatchNumber(s.getBatchNumber());
                                batchSegmentation.setBatchId(s.getBatchId().longValue());
                                batchSegmentation.setSegmentNumber(sub.getSectionNumber());
                                batchSegmentation.setWorkshopId(Long.valueOf(sub.getSectionShopId()));
                                batchSegmentation.setCreatedBy(SecurityUtils.getUsername());
                                batchSegmentationDao.insert(batchSegmentation);
                            } else if (seg > 0) {
                                // 如果找到了对应的批次下的分段
                                BatchSegmentation batchSegmentation = new BatchSegmentation();
                                batchSegmentation.setBatchNumber(s.getBatchNumber());
                                batchSegmentation.setBatchId(s.getBatchId().longValue());
                                batchSegmentation.setSegmentNumber(sub.getSectionNumber());
                                batchSegmentation.setWorkshopId(Long.valueOf(sub.getSectionShopId()));
                                batchSegmentation.setCreatedBy(SecurityUtils.getUsername());
                                batchSegmentationDao.updateBatchAndSegmentation(batchSegmentation);
                            }*/
                            // 如果找到了对应的批次下的分段
                            BatchSegmentation batchSegmentation = new BatchSegmentation();
                            batchSegmentation.setSegmentNumber(sub.getSectionNumber());
                            batchSegmentation.setBeginDate(sub.getSectionBeginDate());
                            batchSegmentation.setEndDate(sub.getSectionEndDate());
                            batchSegmentation.setWorkshopId(Objects.isNull(sub.getSectionShopId()) ? null : Long
                                    .valueOf(sub.getSectionShopId())
                                    .longValue());
                            batchSegmentation.setCreatedBy(SecurityUtils.getUsername());
                            batchSegmentationDao.updateBatchAndSegmentation(batchSegmentation);
                            int batch = batchDao.updateBatches(batches);
                        });
                    }

                });
            }

            if (i > 0) {
                return AjaxResult.success("新增成功");
            }
        }
        return AjaxResult.error("新增失败");
    }

    @Override
    public AjaxResult updateSchedules(Schedules schedules) {
        if (Objects.isNull(schedules)) {
            return AjaxResult.error("入参为空");
        }
        int i = schedulesDao.update(schedules);

        // 判读生产排程下是否有批次
        if (!Objects.isNull(schedules.getSectionBatchedBodies())) {
            schedules.getSectionBatchedBodies().stream().forEach(s -> {
                //int sc = schedulesDao.findBatchesBySchedule(s.getBatchNumber(), schedules.getNumber());
                    /*// 如果没有对应的排程
                    if (sc <= 0) {
                        // 添加批次
                        int batches = batchDao.insertBatchByBatch(new Batches(null, s.getBatchNumber(), null, schedules.getOrderNumber(), null, null, 1, s.getBatchBeginDate(), s.getBatchEndDate(), null, null, null, null, null, Long.valueOf(s.getBatchShopId()), null, s.getBatchWorkshop(), SecurityUtils.getUsername(), null, null, null));
                        scheduleBatchesDao.insert(new ScheduleBatches(null, schedules.getId(), Long.valueOf(batches).longValue(), SecurityUtils.getUsername(), null, null));
                    } else if (sc > 0) {
                        // 如果找到了对应的排程下批次
                        batchDao.updateBatches(new Batches(null, s.getBatchNumber(), null, schedules.getOrderNumber(), null, null, 1, s.getBatchBeginDate(), s.getBatchEndDate(), null, null, null, null, null, Long.valueOf(s.getBatchShopId()), null, s.getBatchWorkshop(), SecurityUtils.getUsername(), null, null, null));
                    }*/
                Batches batches = new Batches();
                batches.setId(s.getBatchId().longValue());
                batches.setNumber(s.getBatchNumber());
                batches.setBeginDate(s.getBatchBeginDate());
                batches.setEndDate(s.getBatchEndDate());
                if (!Objects.isNull(s.getBatchShopId())) {
                    batches.setWorkshopId(s.getBatchShopId().longValue());
                }
                batches.setCreatedBy(SecurityUtils.getUsername());
                int bat = batchDao.updateBatches(batches);
                System.out.println("修改" + bat);
                System.out.println("id：" + batches.getId());
                System.out.println("workshopid：" + batches.getWorkshopId());
                System.out.println("================================");
                // 判断批次下是否有分段
                if (!Objects.isNull(s.getSectionList())) {
                    s.getSectionList().stream().forEach(sub -> {
                        //int seg = batchSegmentationDao.selectBatchAndSegmentation(s.getBatchNumber(), sub.getSectionNumber());
                        // 如果没有对应的批次
                            /*if (seg <= 0) {
                                // 添加分段
                                BatchSegmentation batchSegmentation = new BatchSegmentation();
                                batchSegmentation.setBatchNumber(s.getBatchNumber());
                                batchSegmentation.setBatchId(s.getBatchId().longValue());
                                batchSegmentation.setSegmentNumber(sub.getSectionNumber());
                                batchSegmentation.setWorkshopId(Long.valueOf(sub.getSectionShopId()));
                                batchSegmentation.setCreatedBy(SecurityUtils.getUsername());
                                batchSegmentationDao.insert(batchSegmentation);
                            } else if (seg > 0) {
                                // 如果找到了对应的批次下的分段
                                BatchSegmentation batchSegmentation = new BatchSegmentation();
                                batchSegmentation.setBatchNumber(s.getBatchNumber());
                                batchSegmentation.setBatchId(s.getBatchId().longValue());
                                batchSegmentation.setSegmentNumber(sub.getSectionNumber());
                                batchSegmentation.setWorkshopId(Long.valueOf(sub.getSectionShopId()));
                                batchSegmentation.setCreatedBy(SecurityUtils.getUsername());
                                batchSegmentationDao.updateBatchAndSegmentation(batchSegmentation);
                            }*/
                        // 如果找到了对应的批次下的分段
                        BatchSegmentation batchSegmentation = new BatchSegmentation();
                        batchSegmentation.setId(sub.getSectionId().longValue());
                        batchSegmentation.setSegmentNumber(sub.getSectionNumber());
                        batchSegmentation.setBeginDate(sub.getSectionBeginDate());
                        batchSegmentation.setEndDate(sub.getSectionEndDate());
                        if (!Objects.isNull(sub.getSectionShopId())) {
                            batchSegmentation.setWorkshopId(sub.getSectionShopId().longValue());
                        }
                        batchSegmentation.setCreatedBy(SecurityUtils.getUsername());
                        batchSegmentationDao.updateBatchAndSegmentation(batchSegmentation);
                        int batch = batchDao.updateBatches(batches);
                    });
                }

            });
        }

        if (i > 0) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }

    @Override
    public void schedulesByReport(HttpServletResponse response) {
        List<Schedules> result = schedulesDao.findSchedules(null);
        if (result != null && result.size() > 0) {
            try {
                excelService.downloadBySchedules(Schedules.class, result, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public AjaxResult findScheduleRecords(SchedulesBody schedulesBody) {
        PageHelper.startPage(schedulesBody.getCurrPage(), schedulesBody.getPageSize());
        List<MatterBody> result = schedulesDao.findScheduleRecords(schedulesBody);
        if (result != null && result.size() > 0) {
            result.stream().forEach(r -> {
                r.setParent(1);
            });
            MatterBody matterBody = new MatterBody();
            matterBody.setId(1);
            matterBody.setPlanId(result.get(0).getPlanId());
            matterBody.setPlanNumber(result.get(0).getPlanNumber());
            matterBody.setPlanName(result.get(0).getPlanName());
            matterBody.setOrderNumber(result.get(0).getOrderNumber());
            matterBody.setBatchHour(result.get(0).getBatchHour());
            matterBody.setPlanHour(result.get(0).getPlanHour());
            result.add(matterBody);
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public AjaxResult findApprovals(ApprovalsBody approvalsBody) {
        PageHelper.startPage(approvalsBody.getCurrPage(), approvalsBody.getPageSize());
        List<Approvals> result = approvalsDao.findApprovals(approvalsBody);
        if (result != null && result.size() > 0) {

            if (approvalsBody.isMobileFlag()) {
                // 如果当前用户是管理员
                if (SecurityUtils.getLoginUser().getUser().isAdmin()) {
                    return AjaxResult.success(new PageInfo<>(result
                                                                     .stream()
                                                                     .filter(re -> re
                                                                             .getState()
                                                                             .equals(approvalsBody.getType()))
                                                                     .collect(Collectors.toList())));
                } else {
                    return AjaxResult.success(new PageInfo<>(result
                                                                     .stream()
                                                                     .filter(re -> re
                                                                             .getState()
                                                                             .equals(approvalsBody.getType()) || re
                                                                             .getOperatorId()
                                                                             .equals(SecurityUtils
                                                                                             .getLoginUser()
                                                                                             .getUserId()))
                                                                     .collect(Collectors.toList())));
                }

            }

            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult addApprovals(Approvals approvals) {
        if (!Objects.isNull(approvals)) {
            int i = approvalsDao.insert(approvals);
            if (i > 0) {
                return AjaxResult.success("新增成功");
            }
        }
        return AjaxResult.error("新增失败");
    }

    @Override
    public AjaxResult updateApprovals(Approvals approvals) {
        if (Objects.isNull(approvals)) {
            return AjaxResult.error("入参为空");
        }
        int i = approvalsDao.update(approvals);
        if (i > 0) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }

    @Override
    public void approvalsByReport(HttpServletResponse response) {
        List<Approvals> result = approvalsDao.findApprovals(null);
        if (result != null && result.size() > 0) {
            try {
                excelService.downloadByApprovals(Approvals.class, result, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public AjaxResult findAssignments(AssignmentsBody assignmentsBody) {
        PageHelper.startPage(assignmentsBody.getCurrPage(), assignmentsBody.getPageSize());
        // 是管理员
        if (assignmentsBody.getMobileFlag() != null && assignmentsBody.getMobileFlag() && !SecurityUtils
                .getLoginUser()
                .getUser()
                .isAdmin()) {
//            assignmentsBody.setOperatorId(SecurityUtils.getLoginUser().getUserId());
        }
        List<Assignments> result = assignmentsDao.findAssignments(assignmentsBody);
        if (result != null && result.size() > 0) {
            for (Assignments assignments : result) {
                // todo  写死
                assignments.setPlanName("M660型PCB生产计划");
            }
            return AjaxResult.success(new PageInfo<>(result));
        }

        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public AjaxResult taskStart(Long id) {
        Assignments assignments = assignmentsDao.queryById(id);
        if (assignments == null || assignments.getState() != 1) {
            return AjaxResult.error("该任务不存在，或者该任务状态不为“待处理中”");
        }
        assignments.setState(2L);
        assignments.setFactBeginTime(new Date());
        assignmentsDao.update(assignments);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult taskFinish(Assignments req) {
        Assignments assignments = assignmentsDao.queryById(req.getId());
        if (assignments == null || assignments.getState() != 2) {
            return AjaxResult.error("该任务不存在，或者该任务状态不为“处理中”");
        }

        // 图片
        DispatchPicture picture = new DispatchPicture();
        picture.setNumber(assignments.getId());
        picture.setType(BillTypeEnums.TASK.getCode());
        List<Long> ids = dispatchListDao.queryPictureIds(picture);
        List<DispatchPicture> pictureList = req.getPictureList();
        if (!CollectionUtils.isEmpty(pictureList)) {
            for (DispatchPicture dispatchPicture : pictureList) {
                dispatchPicture.setType(BillTypeEnums.TASK.getCode());
                dispatchPicture.setNumber(req.getId());
            }
            dispatchListDao.dispatchPictureInsertOrUpdate(pictureList);
            // 提出
            if (!CollectionUtils.isEmpty(ids)) {
                for (DispatchPicture dispatchPicture : pictureList) {
                    if (dispatchPicture.getId() != null) {
                        ids.remove(dispatchPicture.getId());
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(ids)) {
            dispatchListDao.deletePictureIds(ids);
        }

        // 任务相关
        List<AssignmentTemplateTask> tasks = req.getTasks();
        Assignments dataBase = findAssignmentsDetail(req.getId());
        List<AssignmentTemplateTask> taskDataBaseList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(tasks)) {
            taskDataBaseList = dataBase.getTasks();
        }
        // 任务项已完成 不为空
        if (!CollectionUtils.isEmpty(tasks)) {
            assignmentTemplateTaskDao.updateTaskState(tasks);
        }
        // 任务项不为空，且任务项和数据库相同
        // 任务为已完成
        Date now = new Date();
        assignments.setState(3L);
        assignments.setFactEndTime(now);
        assignments.setFactHour(DateUtils.diff(assignments.getFactBeginTime(), now));
        assignmentsDao.update(assignments);

        return AjaxResult.success();
    }

    @Override
    public Assignments findAssignmentsDetail(Long id) {
        if (id == null) {
            return null;
        }
        Assignments assignments = assignmentsDao.queryById(id);
        if (assignments == null) {
            return null;
        }
        // 物料
        TaskMaterialApprove taskMaterialApprove = new TaskMaterialApprove();
        taskMaterialApprove.setTaskId(id);
        assignments.setMaterialList(taskMaterialApproveDao.queryAllByEntity(taskMaterialApprove));
        // 图片
        DispatchPicture picture = new DispatchPicture();
        picture.setNumber(id);
        picture.setType(BillTypeEnums.TASK.getCode());
        assignments.setPictureList(dispatchListDao.queryByNumber(picture));

        if (!TaskEventTypeEnums.WORK_ORDER.getCode().equals(Long.valueOf(assignments.getEventType()))) {
            Assignments task = assignmentsDao.queryRelationInfo(assignments);
            if (task != null) {
                assignments.setBatches(task.getBatches());
                assignments.setSegments(task.getSegments());
                assignments.setWorkshopName(task.getWorkshopName());
                assignments.setPlantName(task.getPlantName());
            }
        } else {
            DispatchList dispatchList = new DispatchList();
            dispatchList.setNumber(assignments.getEventNumber());
            List<DispatchList> dispatchLists = dispatchListDao.queryAllByLimit(dispatchList);
            if (!CollectionUtils.isEmpty(dispatchLists)) {
                DispatchList requestDao = dispatchLists.get(0);
                DispatchList dispatch = dispatchListDao.queryRelationInfo(requestDao);
                if (dispatch != null) {
                    assignments.setBatches(dispatch.getBatches());
                    assignments.setSegments(dispatch.getSegments());
                    assignments.setWorkshopName(dispatch.getWorkshopName());
                    assignments.setPlantName(dispatch.getPlantName());
                }
            }
        }
        // todo  写死
        assignments.setPlanName("M660型PCB生产计划");

        if (assignments.getTemplateId() == null || assignments.getId() == null) {
            return assignments;
        }
        // 任务项
        assignments.setTasks(assignmentTemplateTaskDao.queryTasksByTemplateId(assignments));
        return assignments;
    }

    @Override
    public AjaxResult addAssignments(Assignments assignments) {
        if (!Objects.isNull(assignments)) {
            /**
             * 人员登录信息
             */
            AjaxResult ajaxResult = eventTypeCheck(assignments);
            if (ajaxResult != null) {
                return ajaxResult;
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            assignments.setCreatedBy(loginUser.getUsername());
            assignments.setCreatedDate(new Date());
            //任务编号
            assignments.setNumber(SerialNumberUtil.createTaskNo());
            assignments.setClassifyName(questionTypeMap().get(assignments.getClassifyId()));
            int i = assignmentsDao.insert(assignments);
            logger.info("assignments id 为" + assignments.getId());

            /**
             * 获取物料信息 ,物料中间表不为空 insert 物料信息
             */
            List<TaskMaterialApprove> materialsList = assignments.getMaterialList();
            if (!CollectionUtils.isEmpty(materialsList)) {
                // 物料中间表list
                for (TaskMaterialApprove taskMaterialApprove : materialsList) {
                    // 任务编号
                    taskMaterialApprove.setTaskId(assignments.getId());
                    // 物料编号
//                    taskMaterialApprove.setMaterialId(taskMaterialApprove.getId());
                    // 物料数量
//                    taskMaterialApprove.setMaterialCount(taskMaterialApprove.getQuantity());

                    taskMaterialApprove.setCreatedBy(loginUser.getUsername());
                    taskMaterialApprove.setCreatedDate(new Date());
                }
                // 中间表关系
                taskMaterialApproveDao.insertOrUpdateBatch(materialsList);
            }
            /***
             * 获取图片信息 ，有就insert
             */
            List<DispatchPicture> pictureList = assignments.getPictureList();
            if (!CollectionUtils.isEmpty(pictureList)) {
                for (DispatchPicture dispatchPicture : pictureList) {
                    // 任务id
                    dispatchPicture.setNumber(assignments.getId());
                    // 创建人
                    dispatchPicture.setCreatedBy(loginUser.getUsername());
                    dispatchPicture.setCreatedDate(new Date());
                    // 图片类型
                    dispatchPicture.setType(BillTypeEnums.TASK.getCode());
                }
                // 批量insert 图片
                dispatchListDao.dispatchPictureAdd(pictureList);
            }
            // todo 添加任务项模块

            if (i > 0) {
                return AjaxResult.success("新增成功");
            }
        }
        return AjaxResult.error("新增失败");
    }


    public Map<Long, String> questionTypeMap() {
        List<ProductionDict> productionDicts = dispatchListService.questionType();
        Map<Long, String> resMap = new HashMap<>();
        if (CollectionUtils.isEmpty(productionDicts)) {
            return resMap;
        }
        for (ProductionDict productionDict : productionDicts) {
            resMap.put(productionDict.getId(), productionDict.getName());
        }
        return resMap;
    }

    @Override
    public AjaxResult updateAssignments(Assignments assignments) {
        AjaxResult ajaxResult = eventTypeCheck(assignments);
        if (ajaxResult != null) {
            return ajaxResult;
        }
        /**
         * 查询现有图片和物料信息
         */
        // 图片
        DispatchPicture picture = new DispatchPicture();
        picture.setNumber(assignments.getId());
        picture.setType(BillTypeEnums.TASK.getCode());
        List<Long> ids = dispatchListDao.queryPictureIds(picture);
        List<DispatchPicture> pictureList = assignments.getPictureList();
        if (!CollectionUtils.isEmpty(pictureList)) {
            for (DispatchPicture dispatchPicture : pictureList) {
                dispatchPicture.setType(BillTypeEnums.TASK.getCode());
                dispatchPicture.setNumber(assignments.getId());

            }
            dispatchListDao.dispatchPictureInsertOrUpdate(pictureList);
            // 提出
            if (!CollectionUtils.isEmpty(ids)) {
                for (DispatchPicture dispatchPicture : pictureList) {
                    if (dispatchPicture.getId() != null) {
                        ids.remove(dispatchPicture.getId());
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(ids)) {
            dispatchListDao.deletePictureIds(ids);
        }
        // 物料
        TaskMaterialApprove request = new TaskMaterialApprove();
        request.setTaskId(assignments.getId());
        List<Long> taskMaterIds = taskMaterialApproveDao.queryTaskMaterIds(request);
        List<TaskMaterialApprove> materialList = assignments.getMaterialList();
        if (!CollectionUtils.isEmpty(materialList)) {
            for (TaskMaterialApprove taskMaterialApprove : materialList) {
                taskMaterialApprove.setTaskId(assignments.getId());
            }
            taskMaterialApproveDao.insertOrUpdateBatch(materialList);
            if (!CollectionUtils.isEmpty(taskMaterIds)) {
                for (TaskMaterialApprove taskMaterialApprove : materialList) {
                    if (taskMaterialApprove.getId() != null) {
                        taskMaterIds.remove(taskMaterialApprove.getMaterialId());
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(taskMaterIds)) {
            taskMaterialApproveDao.deleteByIds(taskMaterIds);
        }
        // 问题分类
        assignments.setClassifyName(questionTypeMap().get(assignments.getClassifyId()));
        int i = assignmentsDao.update(assignments);

        if (i > 0) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }

    private AjaxResult eventTypeCheck(Assignments assignments) {
        if (Objects.isNull(assignments)) {
            return AjaxResult.error("入参为空 或者 id为空");
        }
        if (assignments.getEventType() == null || !TaskEventTypeEnums.enumTypeExist(Long.valueOf(assignments.getEventType()))) {
            return AjaxResult.error("eventType参数传值有问题");
        }

        Assignments taskEvent = assignmentsDao.taskEventIsExist(assignments.getEventType(), assignments.getEventNumber());
        if (taskEvent == null) {
            return AjaxResult.error(TaskEventTypeEnums.getEnumByType(Long.valueOf(assignments.getEventType())) + "eventeventNumber 不存在");
        }
        assignments.setEventId(taskEvent.getEventId());

        return null;
    }

    @Override
    public void assignmentsByReport(HttpServletResponse response) {
        List<Assignments> result = assignmentsDao.findAssignments(null);
        if (result != null && result.size() > 0) {
            try {
                excelService.downloadByAssignments(Assignments.class, result, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public AjaxResult findProductionByUserId(Integer userId, Integer currPage, Integer pageSize) {
        PageHelper.startPage(currPage, pageSize);
        List<ProductionBody> result = batchDao.findProductionByUserId(userId);
        if (result != null && result.size() > 0) {
            result.stream().forEach(r -> {
                // 要计算占比
                r.setPercentage(0.1);
                r.setTotalNumber(10);
                r.setDoneNumber(1);
                if (StrUtil.isEmpty(r.getDuration())) {
                    r.setDuration("0");
                }
            });
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public AjaxResult findSubsectionByUserId(Integer userId, Integer currPage, Integer pageSize) {
        PageHelper.startPage(currPage, pageSize);
        List<SubsectionBody> result = batchDao.findSubsectionByUserId(userId);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findPlanByUserId(Integer userId) {
        // 完成数
        PlanBody result = assignmentsDao.findPlanByUserId(userId);
        // 塞初始值
        result.initData();
        if (result != null) {
            double divide = 0;
            if (!Double.valueOf(result.getPlanNumber()).equals(0.0)) {
                divide = DoubleOperation.divide(WidgetUtil.setPriceByDecimals(Double.valueOf(result.getComplete())), Double.valueOf(result.getPlanNumber()));
            }
            result.setAchievement(divide);
//            result.setAchievement(WidgetUtil.setPriceByDecimals(Double.valueOf(result.getComplete()) / Double.valueOf(result.getPlanNumber())));

            // 本月1-31号
            LocalDate beginDate = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
            LocalDate endDate = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
            // 上月1-31号
            LocalDate beginLastDate = LocalDate.now().plusMonths(-1).with(TemporalAdjusters.firstDayOfMonth());
            LocalDate endLastDate = LocalDate.now().plusMonths(-1).with(TemporalAdjusters.lastDayOfMonth());

            // 通过率（质检）
            PlanBody getThrough = assignmentsDao.findGetThroughByUserId(userId, beginDate, endDate, beginLastDate, endLastDate);
            if (getThrough != null) {
                double passing = 0;
                if (!Double.valueOf(result.getPlanNumber()).equals(0.0)) {
                    passing = DoubleOperation.divide(WidgetUtil.setPriceByDecimals(Double.valueOf(result.getComplete())), Double.valueOf(result.getPlanNumber()));
                }
//                result.setPassing(WidgetUtil.setPriceByDecimals(Double.valueOf(getThrough.getComplete()) / Double.valueOf(getThrough.getPlanNumber())));
                result.setPassing(passing);
                result.setPassingMonth(getThrough.getPassingMonth());
                result.setPassingLast(getThrough.getPassingLast());
                result.setPassingSvg(getThrough.getPassingSvg());
            }

            // 达成率
            PlanBody resultPlan = assignmentsDao.findPlanByUserIdAndDate(userId, beginDate, endDate, beginLastDate, endLastDate);
            if (resultPlan != null) {
                result.setAchievementMonth(resultPlan.getAchievementMonth());
                result.setAchievementLast(resultPlan.getAchievementLast());
                result.setAchievementSvg(resultPlan.getAchievementSvg());
            }

            return AjaxResult.success(result);
        }
//        return AjaxResult.error("查询失败");
        return AjaxResult.success(new PlanBody());
    }

    @Override
    public AjaxResult findBatchNumberByOrderNumber(Integer orderNumber) {
        List<ComboBoxBody> result = batchDao.findBatchNumberByOrderNumber(orderNumber);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(result);
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findSectionNumberByBatchNumber(Integer batchNumber) {
        List<ComboBoxBody> result = batchDao.findSectionNumberByBatchNumber(batchNumber);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(result);
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findOrderLineDetailsNumber() {
        List<ComboBoxBody> result = batchDao.findOrderLineDetailsNumber();
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findMaterialsClassify() {
        List<ComboBoxBody> result = batchDao.findMaterialsClassify();
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findMaterialsCraft() {
        List<ComboBoxBody> result = batchDao.findMaterialsCraft();
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findAssignmentsByUserId(Integer userId, Integer currPage, Integer pageSize) {
        PageHelper.startPage(currPage, pageSize);
        List<Assignments> result = assignmentsDao.findAssignmentsByUserId(userId);
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(new ArrayList<>()));
    }

    @Override
    public AjaxResult findScheduleBatchesByScheduleId(OrderBody orderBody) {
        PageHelper.startPage(orderBody.getCurrPage(), orderBody.getPageSize());
        List<SectionBatchedBody> result = batchDao.findScheduleBatchesByScheduleId(orderBody.getNumber());
        if (result != null && result.size() > 0) {

            result.stream().forEach(r -> {
                // 根据批次查询排程信息
                List<SectionBody> sectionBodies = batchDao.findBatchScheduleByBatchId(r.getBatchId());
                r.setSectionList(sectionBodies);
            });

            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public AjaxResult findScheduleMaterialByScheduleId(Integer scheduleId) {
        TaskMaterialApprove result = taskMaterialApproveDao.findScheduleMaterialByScheduleId(scheduleId);
        if (result != null) {
            return AjaxResult.success(result);
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findAssignmentTemplateMiddle(Integer approvalId) {
        TaskMaterialApprove result = taskMaterialApproveDao.findAssignmentTemplateMiddle(approvalId);
        if (result != null) {
            return AjaxResult.success(result);
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public List<BaseOrderEntity> queryTaskEventType() {
        List<BaseOrderEntity> list = new ArrayList<>();
        for (TaskEventTypeEnums item : TaskEventTypeEnums.values()) {
            list.add(BaseOrderEntity.builder().name(item.getDesc()).id(item.getCode()).build());
        }
        return list;
    }

    @Override
    public List<BaseOrderEntity> queryTaskEventListByType(Long typeId) {
        if (typeId != null && typeId.equals(0L)) {
            return new ArrayList<>();
        }
        return taskMaterialApproveDao.queryTaskEventListByType(typeId);
    }

    @Override
    public AjaxResult findUserBatchScheduleById() {
        List<BatchScheduleBody> result = batchDao.findBatchSchedule(SecurityUtils
                                                                            .getLoginUser()
                                                                            .getUser()
                                                                            .getUserId()
                                                                            .intValue());
        if (result != null && result.size() > 0) {
            return AjaxResult.success(new PageInfo<>(result));
        }
        return AjaxResult.success(new PageInfo<>(result));
    }

    @Override
    public AjaxResult findUserInformationById() {
        // 本月1-31号
        LocalDate beginDate = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
        LocalDate endDate = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());

        EmpHomepage result = assignmentsDao.findUserInformationById(SecurityUtils
                                                                            .getLoginUser()
                                                                            .getUser()
                                                                            .getUserId()
                                                                            .intValue(), beginDate, endDate);
        if (result != null) {
            result.setTaskSchedule(0.00);
            result.setTaskHour(10.00);
            result.setRejectRatio(0.00);
            result.setTotalNumber(20);
            result.setRejectNumber(0);
            return AjaxResult.success(result);
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public AjaxResult findExamineParticulars(ApprovalsBody approvalsBody) {
        // 查询审批关联的任务编号，去查任务编号下的任务项
        List<ProductionTaskBody> result = approvalsDao.findExamineParticulars(approvalsBody.getId());
        if (result != null && result.size() > 0) {
            return AjaxResult.success(result);
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findOrderParticularsInfo(OrderBody orderBody) {
        List<OrderParticularBody> result = orderDetailsDao.findOrderParticularsInfo(orderBody.getId());
        if (result != null && result.size() > 0) {
            result.stream().forEach(r -> {
                r.setPeopleNumber(r.getBatchCount());
            });
            return AjaxResult.success(result);
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findScheduleParticularsInfo(SchedulesBody schedulesBody) {
        List<ScheduleParticularsBody> result = schedulesDao.findScheduleParticularsInfo(schedulesBody.getId());
        if (result != null && result.size() > 0) {
            return AjaxResult.success(result);
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult updateExamineParticulars(ApprovalsBody approvalsBody) {
        if (Objects.isNull(approvalsBody)) {
            return AjaxResult.error("入参为空");
        }
        // 判断type=1审批通过、type=2审批不通过
        if (approvalsBody.getType().equals(1)) {
            int i = approvalsDao.updateExamineByType(approvalsBody.getId(), 3);
            if (i > 0) {
                return AjaxResult.success("审批通过成功");
            }
        } else if (approvalsBody.getType().equals(2)) {
            int i = approvalsDao.updateExamineByType(approvalsBody.getId(), 4);
            if (i > 0) {
                return AjaxResult.success("审批不通过成功");
            }
        }
        return AjaxResult.error("更新失败");
    }


}
